import React, { Component } from 'react';
import BaseComponent from '@/components/BaseComponent';
import styled from 'styled-components';
import {
  Button,
  Col,
  DatePicker,
  Drawer,
  Form,
  Input,
  message,
  Popconfirm,
  Row,
  Select,
  Upload,
} from 'antd';
import styles from '@/pages/Company/List/Create/index.less';
import { DivFooter, LFlexHDiv } from '@/components/MHtmlTag';
import { defDrawerWidth } from '@/defaultSettings';
import { formatMessage } from 'umi-plugin-react/locale';

const MBody = styled.div`
  .mForm {
  }
`;

const InputDiv = styled.div`
  display: flex;
  width: 100%;
`;

const MLabel = styled.div`
  height: 40px;
  width: 150px;
  display: flex;
  align-items: center;
  padding-left: 8px;
  justify-content: flex-end;
  padding-right: 8px;
`;

const LabelSpan = styled.span`
  color: rgba(0, 0, 0, 0.85);
  font-size: 14px;
`;

const RequiredSpan = styled.span`
  display: inline-block;
  margin-right: 4px;
  color: #f5222d;
  font-size: 14px;
  font-family: SimSun, sans-serif;
  line-height: 1;
`;

/**
 * 输入组件
 * @param props
 * @returns {JSX.Element}
 * @constructor
 */
const MFormInputItem = props => {
  const { fieldName = '', label = '', required = false, form, children } = props;
  const { getFieldDecorator } = form;
  return (
    <InputDiv>
      <MLabel>
        {required ? <RequiredSpan>*</RequiredSpan> : null}
        <LabelSpan>{label}:</LabelSpan>
      </MLabel>
      <Form.Item style={{ flex: '1' }}>
        {children
          ? fieldName != ''
            ? getFieldDecorator(fieldName, {
                rules: [{ required: required, message: label != '' ? `请输入${label}` : '' }],
              })(children)
            : children
          : null}
      </Form.Item>
    </InputDiv>
  );
};

const { TextArea } = Input;
const { Option } = Select;

@Form.create()
class Create extends BaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      // 是否正在上传附件
      uploadLoading: false,
      // 附件列表
      fileList: [],
    };
  }

  render() {
    const { onClose, visible = false, form, projects } = this.props;

    const uploadProps = {
      name: 'file',
      action: `/api/oaservice/v1/oa/uploadJournalFile?username=${this.props.username}`,
      headers: {
        authorization: 'authorization-text',
      },
      onChange: info => {
        if (info.file.status !== 'uploading') {
          this.setState(
            {
              fileList: info.fileList,
            },
            () => {}
          );
        }
        if (info.file.status === 'done') {
          this.successMessage('文件上传成功');
        } else if (info.file.status === 'error') {
          this.errorMessage('文件上传出错,请联系管理员');
        }
      },
    };

    return (
      <Drawer
        title="新增项目日志"
        placement="right"
        width={defDrawerWidth}
        closable={true}
        onClose={e => {
          if (onClose) {
            onClose(e);
          }
        }}
        visible={visible}
      >
        <MBody>
          <div className={'mForm'}>
            <Form>
              <Row>
                <Col span={11}>
                  <MFormInputItem
                    form={form}
                    label={'所属项目'}
                    fieldName={'project_id'}
                    required={true}
                  >
                    <Select placeholder={'请选择所属项目'} style={{ width: '100%' }} allowClear>
                      {projects && projects.length > 0
                        ? projects.map((item, index) => {
                            return (
                              <Option key={index} value={item.id}>
                                {item.projectName}
                              </Option>
                            );
                          })
                        : null}
                    </Select>
                  </MFormInputItem>
                </Col>
                <Col span={11}>
                  <MFormInputItem
                    form={form}
                    label={'记录日期'}
                    fieldName={'record_datetime'}
                    required={true}
                  >
                    <DatePicker placeholder={'请选择'} style={{ width: '100%' }} />
                  </MFormInputItem>
                </Col>
              </Row>

              <Row>
                <Col span={22}>
                  <MFormInputItem
                    form={form}
                    label={'工作内容'}
                    fieldName={'remarks'}
                    required={true}
                  >
                    <TextArea rows={4} style={{ width: '100%' }} />
                  </MFormInputItem>
                </Col>
              </Row>
              <Row>
                <Col span={22}>
                  <MFormInputItem
                    form={form}
                    label={'明日计划内容'}
                    fieldName={'nextplan'}
                    required={true}
                  >
                    <TextArea rows={4} style={{ width: '100%' }} />
                  </MFormInputItem>
                </Col>
              </Row>
              <Row>
                <Col span={22}>
                  <MFormInputItem
                    form={form}
                    label={'附件'}
                    fieldName={'attachment'}
                    required={true}
                  >
                    <Upload
                      {...uploadProps}
                      // disabled={this.state.uploadLoading}
                      // action={`/api/oaservice/v1/oa/uploadJournalFile?username=${this.props.username}`}
                      // onChange={this.handleUploadChange}
                      // fileList={this.state.fileList}
                    >
                      <Button loading={this.state.uploadLoading}>选择文件</Button>
                    </Upload>
                  </MFormInputItem>
                </Col>
              </Row>
            </Form>
          </div>
          <DivFooter>
            <LFlexHDiv>
              <LFlexHDiv flex={'1'} justifyContent={'center'}>
                <Button
                  style={{
                    marginRight: 8,
                    width: '120px',
                  }}
                  onClick={() => {
                    if (onClose) {
                      onClose();
                    }
                  }}
                >
                  取消
                </Button>
                <Popconfirm
                  title="确定执行当前操作吗?"
                  onConfirm={() => {
                    this.handleSubmit();
                  }}
                >
                  <Button type="primary" style={{ width: '120px' }}>
                    新增
                  </Button>
                </Popconfirm>
              </LFlexHDiv>
            </LFlexHDiv>
          </DivFooter>
        </MBody>
      </Drawer>
    );
  }

  /**
   * 处理提交操作
   * @param e
   */
  handleSubmit = () => {
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const { onConfirmClick } = this.props;
        const { fileList } = this.state;
        if (onConfirmClick) {
          // 此处将数据进行一次转换
          const { record_datetime } = values;
          values['record_datetime'] = record_datetime.format('YYYY-MM-DD');
          // 将上传的文件解析出来
          const files = fileList.map((item, index) => {
            const {
              response: {
                data: { filename, url },
              },
            } = item;
            return {
              filename,
              url,
            };
          });
          values['attachment'] = JSON.stringify(files);
          onConfirmClick({ data: values });
        }
      } else {
        console.error('请将信息填写完整');
      }
    });
  };

  /**
   * 字符过滤
   * @param s
   * @returns {string}
   */
  strFilter = s => {
    let pattern = new RegExp(
      "[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）&mdash;—|{}【】‘；：”“'。，、？]"
    );
    let rs = '';
    for (let i = 0; i < s.length; i++) {
      rs = rs + s.substr(i, 1).replace(pattern, '');
    }
    return rs;
  };
}

export default Create;
